<?php

App::uses('AppModel', 'Model');

class CampaignsLocation extends AppModel {
    
    public $belongsTo = array('Location', 'Campaign');
		
	public $hasOne = array(
		'MountPrice' => array(
			'foreignKey' => false,
			'conditions' => array('MountPrice.date <=' => 'CampaignsLocation.start'),
			'order'		 => 'MountPrice.date DESC'
		),
        'Tax' => array(
            'foreignKey' => false,
            'conditions' => array('Tax.effective_date <=' => 'CampaignsLocation.start'),
            'order'      => 'Tax.effective_date DESC'
        )
	);
    
    public $validate = array(
        'start' => array(
            array(
                'rule'    => 'notEmpty',
                'message' => 'Morate uneti datum'
            ),
            array(
                'rule'    => array('verifyDates'),
                'message' => 'Datumi nisu validni'
            )
        ),
        'end' => array(
            array(
                'rule'    => 'notEmpty',
                'message' => 'Morate uneti datum'
            ),
            array (
                'rule'    => array('verifyDates'),
                'message' => 'Datumi nisu validni'
            )
        )
    );
    
    public function afterFind($results, $primary=false) {
        $results = parent::afterFind($results, $primary);
        
        foreach ($results as &$row) {
            if (empty($row['CampaignsLocation']['location_id'])) {
                continue;
            }
            
            if (empty($row['Location'])) {
                $row['Location'] = Set::extract('Location', $this->Location->find('first', array(
                    'conditions' => array('Location.id' => $row['CampaignsLocation']['location_id']),
                    'fields'     => 'Location.*',
                    'recursive'  => 0
                )));
                
                if (! empty($row['Location'])) {
                    $adTypes = $this->Location->AdType->find('all', array(
                        'fields'     => array('AdType.*', 'LocationsAdType.*'),
                        'conditions' => array('LocationsAdType.location_id' => $row['Location']['id']),
                        'joins'      => array(
                            array(
                                'table' => 'locations_ad_types',
                                'alias' => 'LocationsAdType',
                                'type'  => 'INNER',
                                'conditions' => array('LocationsAdType.ad_type_id=AdType.id')
                            )
                        ),
                        'recursive' => 0
                    ));
                    
                    $price = 0;
                    foreach ($adTypes as $adType) {
                        $w = $adType['LocationsAdType']['width'];
                        $h = $adType['LocationsAdType']['height'];
                        $p = $adType['AdType']['price'];
                        $u = $adType['AdType']['unit'];
                        
                        $price += $this->Location->calculatePrice($w, $h, $p, $u);
                    }
                    $row['Location']['price'] = $price;
                }
            }
            
			$row['CampaignsLocation']['price'] = $this->calculatePrice($row);

            $row['Tax'] = $this->loadTax($row);

        }
        
        return $results;
    }

    public function calculatePrice($data, $start=null, $end=null) {
    	$price = (object)array(
    		'production' => 0,
    		'mount'      => 0,
    		'rent'       => 0,
    		'total'      => 0,
    		'numMonths'  => 1
		);
		
        if (empty($data['Location']) || empty($data['CampaignsLocation'])) {
            return $price;
        }
        
		$productionType = (int)$data['CampaignsLocation']['production'];
		
        // production price
        $data = $this->Location->loadAdTypes($data);
		
        if ($productionType == PRODUCTION_ALL) {
			$data['Location']['price'] = $this->Location->loadPrice($data);
	        $price->production         = (float)$data['Location']['price'];
		}
        
        $start = strtotime($data['CampaignsLocation']['start']);
        $end   = strtotime($data['CampaignsLocation']['end']);
        if (!$start || !$end || $end < $start) {
            return $price;
        }
        
        // calculate num of months
        if ($start === null) {
            $start = $data['CampaignsLocation']['start'];
        }
        if ($end === null) {
            $end   = $data['CampaignsLocation']['end'];
        }
        $price->numMonths = calculateNumMonths($start, $end);
		
		// rent price
        $price->rent = (float)@$data['Location']['rent_price'];
		$rabat 		 = (float)$data['CampaignsLocation']['rabat'];
		$avans 		 = (float)$data['CampaignsLocation']['avans'];
		$price->rent *= (1-$rabat/100);
		$price->rent *= (1-$avans/100);
		$price->rent *= $price->numMonths;
		
		// mount_price
		if (in_array($productionType, array(PRODUCTION_MOUNT, PRODUCTION_ALL))) {
			$price->mount = $this->MountPrice->calculate($start, $data);
		}
		
		$price->total = $price->production + $price->mount + $price->rent;
		
        return $price;
    }

    public function loadTax(&$data) {
        if (empty($data['Tax'])) {
            $tax = $this->Tax->find('first', array(
                'fields' => array('Tax.*'),
                'conditions' => array('Tax.effective_date <=' => $data['CampaignsLocation']['start']),
                'recursive' => false
            ));
            $data['Tax'] = $tax['Tax'];
        }
    }
    
    public function verifyDates($data) {
        
        $campaignId = (int)@$this->data[$this->name]['campaign_id'];
        $start      = $this->data[$this->name]['start'];
        $end        = $this->data[$this->name]['end'];
        $locationId = $this->data[$this->name]['location_id'];
        
        $conditions = array(
            "{$this->name}.location_id"   => $locationId,
            'OR' => array(
                "{$this->name}.start BETWEEN '{$start}' AND '{$end}'",
                "{$this->name}.end   BETWEEN '{$start}' AND '{$end}'",
                "{$this->name}.start < '{$start}' AND {$this->name}.end > '{$end}'"
            )
        );
        if ($campaignId) {
            $conditions["{$this->name}.campaign_id !="] = $campaignId;
        }
        
        $count = $this->find('count', array('conditions' => $conditions));
        
        return $count>0 ? false : true;
    }
}
